/**
 * 
 */
package interfaz;

import javax.swing.JPanel;
import java.awt.Frame;
import javax.swing.JDialog;
import java.awt.Rectangle;
import javax.swing.JTree;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Toolkit;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import javax.swing.JSplitPane;
import javax.swing.WindowConstants;
import javax.swing.SwingConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;

import logica.analizador.DocumentoJerarquico;
import logica.estructura.DiedMerger;
import logica.estructura.NTreeDocumento;

/**
 * @author Laura y Renzo
 *
 */
public class Salida extends JDialog {

	private Vector<logica.estructura.Fusion> colores=new Vector<logica.estructura.Fusion>();
	private Frame owner;
	private DefaultMutableTreeNode abuelo;
	private DefaultTreeModel modelo = new DefaultTreeModel(abuelo);
	private String texto1,texto2;
	private boolean esWiki=false;
	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JSplitPane jSplitPane = null;
	private JTree jTree = null;
	private JPanel jPanel = null;
	private JScrollPane jScrollPane = null;
	private JScrollPane jScrollPane1 = null;
	private JTextPane jTextPane = null;
	private JTextPane jTextPane1 = null;
	private JLabel jLabel = null;
	private JLabel jLabel1 = null;
	/**
	 * @param owner
	 */
	public Salida(Frame owner,boolean esWiki,String texto1,String texto2) {
		super(owner);
		this.owner=owner;
		this.esWiki=esWiki;
		this.texto1=texto1;
		this.texto2=texto2;
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setBounds(new Rectangle(0, 0, 744, 228));
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		double fil=dim.getWidth();
		double col=dim.getHeight();
		fil=(fil-700)/2;
		col=(col-228)/2;
		this.setLocation((int)fil, (int)col);
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		this.inicializarArbol();
		this.setContentPane(getJContentPane());
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.fill = GridBagConstraints.BOTH;
			gridBagConstraints.gridy = 0;
			gridBagConstraints.weightx = 1.0;
			gridBagConstraints.weighty = 1.0;
			gridBagConstraints.gridx = 0;
			jContentPane = new JPanel();
			jContentPane.setLayout(new GridBagLayout());
			jContentPane.add(getJSplitPane(), gridBagConstraints);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jSplitPane	
	 * 	
	 * @return javax.swing.JSplitPane	
	 */
	private JSplitPane getJSplitPane() {
		if (jSplitPane == null) {
			jSplitPane = new JSplitPane();
			jSplitPane.setDividerSize(1);
			jSplitPane.setLeftComponent(getJTree());
			jSplitPane.setRightComponent(getJPanel());
			jSplitPane.setDividerLocation(300);
		}
		return jSplitPane;
	}

	/**
	 * This method initializes jTree	
	 * 	
	 * @return javax.swing.JTree	
	 */
	private JTree getJTree() {
		if (jTree == null) {
			jTree = new JTree(modelo);
			jTree.setCellRenderer(new DefaultTreeCellRenderer() {
				private static final long serialVersionUID = 1L;

				public Component getTreeCellRendererComponent(JTree pTree,Object pValue, boolean pIsSelected, boolean pIsExpanded, boolean pIsLeaf, int pRow, boolean pHasFocus)
				  {
				    DefaultMutableTreeNode node = (DefaultMutableTreeNode) pValue;
				    super.getTreeCellRendererComponent(pTree, pValue, pIsSelected, pIsExpanded, pIsLeaf, pRow, pHasFocus);
				    for(int i=0;i<colores.size();i++)
				    {
				    	if (node.getUserObject().equals(colores.elementAt(i).getTexto()))
				    	{
				    		if(colores.elementAt(i).getColor()==1)
				    		{
				    			setForeground(Color.BLUE);
				    		}
				    		if(colores.elementAt(i).getColor()==1)
				    		{
				    			setForeground(Color.RED);
				    		}
				    	}
				    }
				    return (this);
				  }
				});

		}
		return jTree;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			jLabel1 = new JLabel();
			jLabel1.setBounds(new Rectangle(226, 14, 200, 16));
			jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
			jLabel1.setText("Texto 2");
			jLabel = new JLabel();
			jLabel.setBounds(new Rectangle(15, 14, 200, 16));
			jLabel.setHorizontalAlignment(SwingConstants.CENTER);
			jLabel.setText("Texto 1");
			jPanel = new JPanel();
			jPanel.setLayout(null);
			jPanel.add(getJScrollPane(), null);
			jPanel.add(getJScrollPane1(), null);
			jPanel.add(jLabel, null);
			jPanel.add(jLabel1, null);
		}
		return jPanel;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setBounds(new Rectangle(15, 37, 200, 145));
			jScrollPane.setViewportView(getJTextPane1());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jScrollPane1	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane1() {
		if (jScrollPane1 == null) {
			jScrollPane1 = new JScrollPane();
			jScrollPane1.setBounds(new Rectangle(226, 37, 200, 145));
			jScrollPane1.setViewportView(getJTextPane());
		}
		return jScrollPane1;
	}

	/**
	 * This method initializes jTextPane	
	 * 	
	 * @return javax.swing.JTextPane	
	 */
	private JTextPane getJTextPane() {
		if (jTextPane == null) {
			jTextPane = new JTextPane();
			jTextPane.setEditable(false);
		}
		return jTextPane;
	}

	/**
	 * This method initializes jTextPane1	
	 * 	
	 * @return javax.swing.JTextPane	
	 */
	private JTextPane getJTextPane1() {
		if (jTextPane1 == null) {
			jTextPane1 = new JTextPane();
			jTextPane1.setEditable(false);
		}
		return jTextPane1;
	}
	
	private void inicializarArbol()
	{
		try {
			DocumentoJerarquico dJ;
			dJ = new DocumentoJerarquico(texto1);
			NTreeDocumento nTDoc = new NTreeDocumento(dJ.getTitulo());
			nTDoc.createTreeFromRoot(nTDoc, dJ);
			this.getJTextPane1().setText(nTDoc.renderizar(this.esWiki, 0, 1));
			DocumentoJerarquico dJ1;
			dJ1 = new DocumentoJerarquico(texto2);
			NTreeDocumento nTDoc1 = new NTreeDocumento(dJ1.getTitulo());
			nTDoc1.createTreeFromRoot(nTDoc1, dJ1);
			
			NTreeDocumento aResultado = nTDoc.fusionarArboles(nTDoc1);
			
			Vector<String> parametros=new Vector<String>();
			{
				String opcion="contarpalabras = true";
				parametros.addElement(opcion);
			}
			
			String resultado="";
			
			try
			{
				resultado=DiedMerger.merge(this.getJTextPane1().getText(), nTDoc1.renderizar(this.esWiki, 0, 1), parametros, ((Principal)this.owner).getSeparadores());
			} catch(Exception e) {
				JOptionPane.showMessageDialog(this, "Se ha producido un error inesperado", "Error", 0);
			}

			this.colorearTexto(resultado);
			
			//Original
//			abuelo = new DefaultMutableTreeNode(nTDoc.value().toString());
//			modelo = new DefaultTreeModel(abuelo);
//			this.iniMutableTree(modelo, abuelo, nTDoc.childs());
			
			//Arbol Fusionado
			abuelo = new DefaultMutableTreeNode(aResultado.value().toString());
			modelo = new DefaultTreeModel(abuelo);
			this.iniMutableTree(modelo, abuelo, aResultado.childs());

			
/*		
			DefaultMutableTreeNode padre = new DefaultMutableTreeNode("padre");
			DefaultMutableTreeNode tio = new DefaultMutableTreeNode("tio");
			DefaultMutableTreeNode hijo=new DefaultMutableTreeNode("hijo");
			DefaultMutableTreeNode hija=new DefaultMutableTreeNode("hija");
			modelo.insertNodeInto(padre,abuelo,0);
			modelo.insertNodeInto(tio, abuelo, 1);
			modelo.insertNodeInto(hijo, padre, 0);
			modelo.insertNodeInto(hija, padre, 1);
*/
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, "Se ha producido un error inesperado", "Error", 0);
		}
	}
	
	private void colorearTexto(String texto)
	{
//		creamos la clase StyleContext en la que nos apoyaremos
		StyleContext sc = new StyleContext();

//		primer tipo de estilo... color rojo
		Style estiloRojo = sc.addStyle(null, null);
		StyleConstants.setForeground(estiloRojo, new Color(213,51,43));
//		tambien existen los método setBackground(), setFont()

//		para el negro
		Style estiloNegro = sc.addStyle(null, null);
		StyleConstants.setForeground(estiloNegro, Color.black);

//		creamos el StyledDocument pasandole la clase
//		StyleContext que hemos creado antes...
		DefaultStyledDocument doc = new DefaultStyledDocument(sc);
		
		JTextPane texto1 = new JTextPane(doc); 
		this.jTextPane=texto1;
		
		try {
			int aux=texto.indexOf("\\dif:Texto1{");
			int aux1=texto.indexOf("}Texto2{")+8;
			int aux2;
			String textoAux;
			while (aux!=-1)
			{
				doc.insertString(doc.getLength(), texto.substring(0, aux), estiloNegro);
				textoAux=texto.substring(aux1, texto.length());
				aux2=textoAux.indexOf("}")+aux1;
				doc.insertString(doc.getLength(), texto.substring(aux1, aux2-1), estiloRojo);
				texto=texto.substring(aux2+1, texto.length());
				aux=texto.indexOf("\\dif:Texto1{");
				aux1=texto.indexOf("}Texto2{")+8;
			}
			doc.insertString(doc.getLength(), texto.substring(0, texto.length()), estiloNegro);
		} catch (BadLocationException e) {
			e.printStackTrace();
		} 
		
		
	}
	
	
	
	/**
	 * Esta funcion crea el Mutable Tree para mostar en la UI
	 * @param modelo
	 * @param padre
	 * @param childs
	 */
	private void iniMutableTree(DefaultTreeModel modelo, DefaultMutableTreeNode padre, Vector<?> childs)
	{
		if (childs.size()>0)
		{
			for (int i=0; i<childs.size(); i++)
			{	
				DefaultMutableTreeNode hijo;
				NTreeDocumento aNTdoc = (NTreeDocumento)childs.elementAt(i);
				
				if (aNTdoc.value() instanceof logica.estructura.Fusion)
				{
					hijo = new DefaultMutableTreeNode(((logica.estructura.Fusion)aNTdoc.value()).getTexto());
					colores.addElement((logica.estructura.Fusion)aNTdoc.value());
				}
				else
				{
					hijo = new DefaultMutableTreeNode(aNTdoc.value());
				}
				
				modelo.insertNodeInto(hijo , padre, i);
				this.iniMutableTree(modelo, hijo, aNTdoc.childs());
			}
		}
	}
	
}  //  @jve:decl-index=0:visual-constraint="95,2"
